package com.spring.sunflower.userinfo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.STSCertBean;
import com.spring.sunflower.bean.VideoListBean;
import com.spring.sunflower.bean.VideoShowReleaseBean;
import com.spring.sunflower.common.CommonContract;
import com.spring.sunflower.common.FileUploadCallback;
import com.spring.sunflower.common.VideoPlayActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.util.AliUploadUtils;
import com.spring.sunflower.util.PathUtils;

import org.jetbrains.annotations.NotNull;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Kevin on 2021/7/2<br/>
 * <p>
 * Describe:<br/>
 */
public class VideoShowListActivity extends BaseActivity<VideoShowListPresenter> implements CommonContract.VideoShowListView {
    private RecyclerView recyclerView;
    private String keyID;
    private String keySecret;
    private String securityToken;
    private List<VideoListBean.DatasBean> mData = new ArrayList<>();
    private VideoShowListAdapter mAdapter;
    private AliUploadUtils aliUploadUtils;
    private boolean hasAddButton = false;
    private MediaMetadataRetriever metadataRetriever;
    private String videoFirstPath = "", videoPath = "";

    @Override
    public void initView() {
        String userId = getField(Constant.KEY_USERID, "");
        Intent intent = getIntent();
        keyID = intent.getStringExtra(Constant.ALI_KEY_ID);
        keySecret = intent.getStringExtra(Constant.ALI_KEY_SECRET);
        securityToken = intent.getStringExtra(Constant.ALI_SECURITY_TOKEN);
        if (TextUtils.isEmpty(keyID) || TextUtils.isEmpty(keySecret) || TextUtils.isEmpty(securityToken)) {
            mPresenter.getSTSCert();
        } else {
            aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
        }
        metadataRetriever = new MediaMetadataRetriever();

        tvTitle.setText("视频秀");
        recyclerView = findViewById(R.id.rvRecyclerView);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        mAdapter = new VideoShowListAdapter(R.layout.adapter_item_video_list, mData);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                VideoListBean.DatasBean datasBean = mData.get(position);
                if (datasBean.isPlaceHolder()) {
                    checkOpenGalleryVideo(VideoShowListActivity.this);
                    //上传照片
//                    PictureSelector.create(VideoShowListActivity.this)
//                            .openGallery(PictureMimeType.ofVideo())
//                            .imageEngine(GlideEngine.createGlideEngine())/**/
//                            .isWeChatStyle(true)
//                            .maxSelectNum(1)
//                            .selectionMode(PictureConfig.SINGLE)
//                            .videoMaxSecond(30)
//                            .videoMinSecond(6)
//                            .isCamera(true)
//                            .forResult(PictureConfig.CHOOSE_REQUEST);

                } else {
                    Intent intent = new Intent(VideoShowListActivity.this, VideoPlayActivity.class);
                    intent.putExtra("currentIndex", position);
                    intent.putExtra("otherId", userId);
                    startActivity(intent);
                }
                List<VideoListBean.DatasBean> data = new ArrayList<>();
                for (VideoListBean.DatasBean bean : mData) {
                    bean.setShowDelete(false);
                    data.add(bean);
                }
                mAdapter.setList(data);
            }
        });

        mAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                List<VideoListBean.DatasBean> data = new ArrayList<>();
                for (VideoListBean.DatasBean bean : mData) {
                    bean.setShowDelete(true);
                    data.add(bean);
                }
                mAdapter.setNewInstance(data);
                return true;
            }
        });
//        mAdapter.addChildClickViewIds(R.id.ivPlay);
        mAdapter.addChildClickViewIds(R.id.rivDelete);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                switch (view.getId()) {
                    case R.id.rivDelete:
//                        showToast("mData.size=" + mData.size());
                        VideoListBean.DatasBean datasBean = mData.get(position);
                        Map<String, String> map = new HashMap<>();
                        map.put("videoId", datasBean.getId());
                        mPresenter.deleteVideo(map, position);
                        break;
                    case R.id.ivPlay:
                        Intent intent = new Intent(VideoShowListActivity.this, VideoPlayActivity.class);
                        intent.putExtra("currentIndex", position);
                        intent.putExtra("otherId", userId);
                        startActivity(intent);
                        break;
                }
            }
        });
        queryVideoX();
    }

    private void queryVideoX() {
        String userId = getField(Constant.KEY_USERID, "");
        Map<String, String> map = new HashMap<>();
        map.put("memberId", userId);
        map.put("pageIndex", "1");
        mPresenter.queryVideo(map);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_video_show_list;
    }

    @Override
    public VideoShowListPresenter setPresenter() {
        return new VideoShowListPresenter(this);
    }

    @Override
    public void updateSuccess(VideoShowReleaseBean.DatasBean bean) {
        VideoListBean.DatasBean dataBean = new VideoListBean.DatasBean();
        dataBean.setId(bean.getId());
        dataBean.setMemberId(bean.getMemberId());
        dataBean.setVideoPath(bean.getVideoPath());
        dataBean.setCommentTotal(bean.getCommentTotal());
        dataBean.setLikeTotal(bean.getLikeTotal());
        dataBean.setBrowseTotal(bean.getBrowseTotal());
        dataBean.setIsVerify(bean.getIsVerify());
        dataBean.setDescribe(bean.getDescribe());
        dataBean.setCity(bean.getCity());
        dataBean.setRecommend(bean.getRecommend());
        dataBean.setVideoFirstPhotoUrl(bean.getVideoFirstPhotoUrl());
        dataBean.setPlaceHolder(false);
        if (mData.size() == 8) {
            mAdapter.removeAt(7);
            mAdapter.addData(dataBean);
            hasAddButton = false;
        } else {
            printD("mData="+mData.size());
            int pos = mData.size() - 1;
            mAdapter.addData(pos,dataBean);
            printD("ssss="+mAdapter.getData().size());
            printD("count"+mAdapter.getItemCount()+"，="+mData.size());
        }
    }

    @Override
    public void updateFailed() {

    }

    @Override
    public void querySuccess(List<VideoListBean.DatasBean> data) {
        Collections.reverse(data);
        printD("data="+data.size());
        mAdapter.addData(data);
        printD("data mData000="+mData.size());
        if (data.size() < 8) {
            VideoListBean.DatasBean bean = new VideoListBean.DatasBean();
            bean.setPlaceHolder(true);
            mAdapter.addData(bean);
            printD("data mData="+mData.size());
            hasAddButton = true;
        } else {
        }
    }

    @Override
    public void queryFailed() {

    }

    @Override
    public void deleteSuccess(int position) {
        mAdapter.removeAt(position);
        mData.remove(position);
        printD("deleteSuccess="+mData.size());
        List<VideoListBean.DatasBean> data = new ArrayList<>();
        for (VideoListBean.DatasBean bean : mAdapter.getData()) {
            bean.setShowDelete(false);
            data.add(bean);
        }
        mAdapter.setNewInstance(data);
        if (!hasAddButton) {
            VideoListBean.DatasBean bean = new VideoListBean.DatasBean();
            bean.setPlaceHolder(true);
            mAdapter.addData(bean);
        }
    }

    @Override
    public void deleteFailed() {

    }

    @Override
    public void loadSTSCert(STSCertBean.DatasBean data) {
        keyID = data.getAccessKeyId();
        keySecret = data.getAccessKeySecret();
        securityToken = data.getSecurityToken();
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                if (data != null) {
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : localMedia) {
//                        String path =
                        uploadVideo(media);
                    }
                }
            }
        }
    }

    private void uploadVideo(LocalMedia media) {
        showLoading();
        String path = media.getPath();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            path = PathUtils.getPath(VideoShowListActivity.this, Uri.parse(path));
        }
        metadataRetriever.setDataSource(path);
        Bitmap bitmap = metadataRetriever.getFrameAtTime();
        String tempPath = getCacheDir() + "/" + System.currentTimeMillis() + ".png";
        try {
            FileOutputStream fos = new FileOutputStream(tempPath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
            fos.flush();
            fos.close();
            bitmap.recycle();
            aliUploadUtils.upLoadFile(tempPath, new FileUploadCallback() {
                @Override
                public void onFailure(String str) {
                }

                @Override
                public void onSuccess(Object paramRequestString, String filePath) {
                    videoFirstPath = filePath;
//                    releaseVideo();
                }

                @Override
                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                }
            });
            aliUploadUtils.upLoadFile(path, new FileUploadCallback() {
                @Override
                public void onFailure(String str) {
                    hideLoading();
                }

                @Override
                public void onSuccess(Object paramRequestString, String filePath) {
                    hideLoading();
                    videoPath = filePath;
                    releaseVideo();
                }

                @Override
                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            hideLoading();
            showToast("上传失败:(" + e.getMessage());
        } catch (IOException e) {
            hideLoading();
            e.printStackTrace();
            showToast("上传失败:(" + e.getMessage());
        }

    }

    private void releaseVideo() {
        String userId = getField(Constant.KEY_USERID, "");
        if (!TextUtils.isEmpty(videoFirstPath) && !TextUtils.isEmpty(videoPath)) {
            Map<String, String> map = new HashMap<>();
            map.put("memberId", userId);
            map.put("videoFirstPhotoUrl", videoFirstPath);
            map.put("videoPath", videoPath);
            mPresenter.releaseVideo(map);
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, UserInfoEditActivity.class);
        intent.putExtra(Constant.USER_VIDEO_LIST, (Serializable) mAdapter.getData());
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }
}
